<?php
namespace app\jzshop\common;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class Jwts
{
    private $privateKey = <<<EOD
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQC24+m/9qFTKYbFgg8iAUn0aY09htNtuCqd4F0439qgZOKosLU/
kstxki0aPsLLIM5J7xsco/z5ThqEVwEzg9rtmb968O2z+x18QfOZ4ywFn/2ytQey
isuAZyGVHE0EQIRLoRmZT6iLgficYHbmTLhh2LtkmtZVYyjIttJrUVD88QIDAQAB
AoGBAIP2CPgIhTiTEvo5sJ+RnIHtEwsc2DsnkiBd/gWGh6IJiP28mtqnGYH1vfNc
64JTRmVUUBSnQmXD9CAfAu/fqLtkDMJrUNeHWYwJJVR3J23rGQrwFQQB00WfG2ON
6FHEIzfKpJvZ0Rpf9qYD5E/D0bZpkrGoWKYtN0uQE3GULTE9AkEA7TKlDDpfUwUK
lAaqbXsZFp5DJoUdFTJmhxDozlROG0f1hW35H5Xk6Pc+TTfQT2QoEFWNThSJGjIq
BsWmPOo4twJBAMVjOnKsuKnuKn7jjjL3mwISk5nK59ddCz7ItyADz7vYp0LN4v28
bit4A+2LFgKxAr69NlfpwQk1XzF3LdDvv5cCQH8xZC3tc0ZqcqSz+lng47AsR6f1
Q4YlU7NjzuMtdADPEoptUWStlWWTh1YS8uJPu+geaDqRan+gnMaq4BzUIHsCQE2K
Qn6j7VML9XOtTsIk1KbGx2bl95d5vJ4oWQ/hj2x6mpI6sQ3+RMUcu2ZIehgKk0p8
p+l3MVa9uayD5eKrG/cCQBBqa8VwDefmnlxZcTIm7AsdFYc+OD0l3dBuYXMLxZA9
jaf7THRzl2NdVee9BPjWTc626iDpmVVMjnVw81ofQLo=
-----END RSA PRIVATE KEY-----
EOD;

    private $publicKey = <<<EOD
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC24+m/9qFTKYbFgg8iAUn0aY09
htNtuCqd4F0439qgZOKosLU/kstxki0aPsLLIM5J7xsco/z5ThqEVwEzg9rtmb96
8O2z+x18QfOZ4ywFn/2ytQeyisuAZyGVHE0EQIRLoRmZT6iLgficYHbmTLhh2Ltk
mtZVYyjIttJrUVD88QIDAQAB
-----END PUBLIC KEY-----
EOD;
    private static $instance;
    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    public function Create($payload = [])
    {
        $jwt = JWT::encode($payload, $this->privateKey, 'RS256');

        return $this->base64Encode($jwt);
    }


    public function CheckJwt($jwt = '')
    {
        $jwt = $this->base64Decode($jwt);
        if ($jwt == '') {
            return false;
        }
        $decoded = JWT::decode($jwt, new Key($this->publicKey, 'RS256'));
        $decoded_array = (array) $decoded;
        return $decoded_array;

    }
    private static $keysmap = [
        'start' => 'qweerfvxmijjrtiafh89925^@*#$*',
        'end' => 'asdfgjtir5yhydk^@*r#$aeargrdg33*',
    ];

    public static function base64Encode($str)
    {
        if (empty($str)) {
            return '';
        }
        $str = self::$keysmap['start'] . $str . self::$keysmap['end'];
        $bsse64_str = base64_encode($str);
        return $bsse64_str;
    }

    public static function base64Decode($str)
    {
        $bsse64_str = base64_decode($str, true);
        if ($bsse64_str === false) {
            echo "Error decoding Base64\n";
            return '';
        }
        $bsse64_str0 = str_replace(self::$keysmap['start'], '', $bsse64_str);
        $bsse64_str1 = str_replace(self::$keysmap['end'], '', $bsse64_str0);
        return $bsse64_str1;
    }

}